﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Mes.车间机床
{
    public partial class AddMachineForm : Form
    {
        private readonly int? _workshopId; // 车间ID
        public AddMachineForm()
        {
            InitializeComponent();
        }

        public AddMachineForm(int? workshopId) : this()
        {
            _workshopId = workshopId;
        }


        private string uploadedImagePath; // 存储上传后的图片路径
        private async void skinPictureBox1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                Filter = "Image Files|*.jpg;*.png",
                Title = "选择设备图片"
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                skinPictureBox1.Image = Image.FromFile(openFileDialog.FileName);

                // 直接上传文件到后端
                using (HttpClient client = new HttpClient())
                {
                    string apiUrl = "http://10.223.8.11:8083/api/File/UploadFile";
                    byte[] imageBytes = File.ReadAllBytes(openFileDialog.FileName);
                    var content = new MultipartFormDataContent();
                    content.Add(new ByteArrayContent(imageBytes), "file", openFileDialog.SafeFileName);

                    // 发送 POST 请求
                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    if (response.IsSuccessStatusCode)
                    {
                        // 后端返回的是纯文本（预签名 URL），直接读取
                        string fullPath = (await response.Content.ReadAsStringAsync())?.Trim().Trim('"');
                        
                        // 保存简短的图片标识符，既能满足数据库长度限制，又能用于显示
                        if (!string.IsNullOrEmpty(fullPath))
                        {
                            // 生成一个简短的图片标识符：时间戳_原始文件名
                            string timestamp = DateTime.Now.ToString("yyyyMMddHHmmss");
                            string originalFileName = openFileDialog.SafeFileName;
                            string extension = Path.GetExtension(originalFileName);
                            string nameWithoutExt = Path.GetFileNameWithoutExtension(originalFileName);
                            
                            // 限制文件名长度，确保总长度不超过50字符
                            if (nameWithoutExt.Length > 30)
                            {
                                nameWithoutExt = nameWithoutExt.Substring(0, 30);
                            }
                            
                            // 格式：时间戳_文件名.扩展名
                            uploadedImagePath = $"{timestamp}_{nameWithoutExt}{extension}";
                            
                            // 确保总长度不超过50字符
                            if (uploadedImagePath.Length > 50)
                            {
                                uploadedImagePath = uploadedImagePath.Substring(0, 50);
                            }
                            
                            // 确保Images目录存在
                            string imagesDirectory = Path.Combine(Application.StartupPath, "Images");
                            if (!Directory.Exists(imagesDirectory))
                            {
                                Directory.CreateDirectory(imagesDirectory);
                            }
                            
                            // 将原始图片文件复制到Images目录
                            string targetPath = Path.Combine(imagesDirectory, uploadedImagePath);
                            File.Copy(openFileDialog.FileName, targetPath, true);
                        }
                        
                        MessageBox.Show($"图片上传成功！\n完整路径: {fullPath}\n存储标识: {uploadedImagePath}\n保存位置: {Path.Combine(Application.StartupPath, "Images", uploadedImagePath)}");
                    }
                    else
                    {
                        MessageBox.Show($"图片上传失败：{response.StatusCode}");
                    }
                }
            }
        }

        private async void btnAdd_Click(object sender, EventArgs e)
        {
            // 验证WorkshopId
            if (_workshopId == null || _workshopId <= 0)
            {
                MessageBox.Show("错误：未获取到有效的车间ID，请先在车间列表选中一条记录！");
                return;
            }

            // 验证图片是否已上传
            if (string.IsNullOrEmpty(uploadedImagePath))
            {
                MessageBox.Show("请先上传设备图片！");
                return;
            }
            // 表单必填校验
            if (string.IsNullOrWhiteSpace(textMachineName.Text)) { MessageBox.Show("请填写设备名称"); return; }
            if (string.IsNullOrWhiteSpace(comMachineType.Text)) { MessageBox.Show("请选择设备类型"); return; }
            if (string.IsNullOrWhiteSpace(comMachineState.Text)) { MessageBox.Show("请选择设备状态"); return; }
            if (string.IsNullOrWhiteSpace(comshengcai.Text)) { MessageBox.Show("请选择生产线"); return; }
            if (string.IsNullOrWhiteSpace(textAdd.Text)) { MessageBox.Show("请填写添加人"); return; }

            // 收集设备信息
            // 编号：如果文本框为占位，则自动生成一个
            string machineCodeToSend = (textMachineCode.Text != null && textMachineCode.Text.Trim() != "保存后自动生成")
                ? textMachineCode.Text.Trim()
                : ($"MC{DateTime.Now:yyyyMMddHHmmss}");

            // 组装业务数据（使用后端要求的帕斯卡命名法）
            var machineData = new
            {
                MachineToolCode = machineCodeToSend,
                MachineToolName = textMachineName.Text?.Trim(),
                MachineToolType = (comMachineType.SelectedItem ?? comMachineType.Text)?.ToString(),
                MachineToolStates = (comMachineState.SelectedItem ?? comMachineState.Text)?.ToString(),
                ProductionLines = (comshengcai.SelectedItem ?? comshengcai.Text)?.ToString(),
                ProcurementDate = DateTime.Now.ToString("yyyy-MM-dd"), // 简化日期格式
                AddPeople = textAdd.Text?.Trim(),
                AddDate = DateTime.Now.ToString("yyyy-MM-dd"), // 简化日期格式
                Img = uploadedImagePath,
                WorkshopId = _workshopId.Value
            };

            // 直接发送数据，不包装在request对象中
            // var requestData = new { request = machineData };

            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.DefaultRequestHeaders.Authorization =
                       new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    // 尝试不同的API地址
                    string apiUrl = "https://localhost:7084/api/Machine/AddMachine";
                    
                    // 设置请求头
                    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                    client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
                    
                    // 序列化并显示调试信息
                    string jsonData = JsonConvert.SerializeObject(machineData, Formatting.Indented);
                    Console.WriteLine($"发送的JSON数据:\n{jsonData}");
                    Console.WriteLine($"API地址: {apiUrl}");
                    Console.WriteLine($"WorkshopId: {_workshopId}");
                    
                    // 显示每个字段的值
                    Console.WriteLine($"字段值检查:");
                    Console.WriteLine($"MachineToolCode: '{machineCodeToSend}'");
                    Console.WriteLine($"MachineToolName: '{textMachineName.Text?.Trim()}'");
                    Console.WriteLine($"MachineToolType: '{(comMachineType.SelectedItem ?? comMachineType.Text)?.ToString()}'");
                    Console.WriteLine($"MachineToolStates: '{(comMachineState.SelectedItem ?? comMachineState.Text)?.ToString()}'");
                    Console.WriteLine($"ProductionLines: '{(comshengcai.SelectedItem ?? comshengcai.Text)?.ToString()}'");
                    Console.WriteLine($"AddPeople: '{textAdd.Text?.Trim()}'");
                    Console.WriteLine($"Img: '{uploadedImagePath}'");
                    Console.WriteLine($"WorkshopId: {_workshopId.Value}");
                    
                    var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                    // 发送请求前显示信息
                    MessageBox.Show($"准备发送请求到: {apiUrl}\nWorkshopId: {_workshopId}\n数据长度: {jsonData.Length}字符\n\n字段值:\nMachineToolCode: {machineCodeToSend}\nMachineToolName: {textMachineName.Text?.Trim()}\nMachineToolType: {(comMachineType.SelectedItem ?? comMachineType.Text)?.ToString()}\nMachineToolStates: {(comMachineState.SelectedItem ?? comMachineState.Text)?.ToString()}\nProductionLines: {(comshengcai.SelectedItem ?? comshengcai.Text)?.ToString()}\nAddPeople: {textAdd.Text?.Trim()}\nImg: {uploadedImagePath}");

                    HttpResponseMessage response = await client.PostAsync(apiUrl, content);

                    // 显示响应头信息
                    Console.WriteLine($"响应状态码: {response.StatusCode}");
                    Console.WriteLine($"响应头: {string.Join(", ", response.Headers.Select(h => $"{h.Key}={string.Join(";", h.Value)}"))}");

                    if (response.IsSuccessStatusCode)
                    {
                        string successResponse = await response.Content.ReadAsStringAsync();
                        MessageBox.Show($"设备添加成功！\n响应内容: {successResponse}");
                        // 通知父窗体刷新
                        this.DialogResult = DialogResult.OK;
                        this.Close();
                    }
                    else
                    {
                        string errorResponse = await response.Content.ReadAsStringAsync();
                        string fullError = $"添加失败：{response.StatusCode}\r\n状态码：{response.StatusCode}\r\n响应内容：{errorResponse}\r\n响应头：{string.Join(", ", response.Headers.Select(h => $"{h.Key}={string.Join(";", h.Value)}"))}";
                        MessageBox.Show(fullError);
                        Console.WriteLine($"错误响应:\n{fullError}");
                    }
                }
            }
            catch (Exception ex)
            {
                string errorMsg = $"发生错误：{ex.Message}\r\n堆栈跟踪：{ex.StackTrace}";
                MessageBox.Show(errorMsg);
                Console.WriteLine($"异常信息:\n{errorMsg}");
            }
        }
    }
}
